<template>

<el-dialog
    v-model="inputValue"
    title="导入通信塔数据"
    width="500"
  >
  <div>
    <!-- 文件上传组件 -->
    <el-upload
      :file-list="fileList"
      :limit="1"
      :auto-upload="false"
      accept=".xlsx,.xls"
      :on-change="handleFileChange"
    >
            <el-button type="primary">选择文件</el-button>
              <template #tip>
                <div class="el-upload__tip">请上传 .xlsx 或 .xls 文件</div>
              </template>
            </el-upload>
  </div>
  <template #footer>
            <div class="dialog-footer">
            <el-button @click=" inputValue= false">取消</el-button>
            <el-button type="primary" @click="upLoadMessage2">
                确定
            </el-button>
            </div>
        </template>
  </el-dialog>

    <div class="container">
      <el-select  v-model="inputCity" placeholder="选择地市" style="width: 240px">
      <el-option
        v-for="item in Prefectures"
        :label="item.label"
        :value="item.value"
      />
      </el-select>
      <el-select v-model="inputCounty" placeholder="选择区县" style="width: 240px;margin-left:2rem;" filterable
        clearable
       >
      <el-option
        v-for="item in citys"
        :label="item.label"
        :value="item.value"
      />
      </el-select>
        <el-select v-model="inputTowerTypeId" placeholder="选择通信塔类型" style="width: 240px;margin-left: 2rem" filterable
  clearable>
            <el-option
            v-for="item in towerTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
        </el-select>

        <el-input v-model="inputTowerName" style="width: 240px;margin-left: 2rem" placeholder="站点名称" />

        <div style="margin-top: 1rem;">
          <el-button style="width: 6rem;background-color: rgba(110, 78, 208, 0.1); border-color: #6f42c1; color: rgb(110, 78, 208);"type="primary"  @click="filterUser">查询</el-button>
          <el-button style="width: 6rem;margin-left: 2rem;background-color: rgba(110, 78, 208, 0.1); border-color: #6f42c1; color: rgb(110, 78, 208);" type="primary" @click="installTower()"  v-if="hasPermission(authStore.permissions,15)">下载导入模板</el-button>
          <el-button style="width: 6rem;margin-left: 2rem;background-color: rgba(110, 78, 208, 0.1); border-color: #6f42c1; color: rgb(110, 78, 208);" type="primary" @click="inputTower()"  v-if="hasPermission(authStore.permissions,16)">导入</el-button>
          <el-button style="width: 6rem;margin-left: 2rem;background-color: rgba(110, 78, 208, 0.1); border-color: #6f42c1; color: rgb(110, 78, 208);" type="primary" @click="outputTower()"  v-if="hasPermission(authStore.permissions,17)">导出</el-button>
          <el-button style="width: 6rem;margin-left: 2rem;background-color: rgba(110, 78, 208, 0.1); border-color: #6f42c1; color: rgb(110, 78, 208);" type="primary" @click="addTower()"   v-if="hasPermission(authStore.permissions,18)">新建通信塔</el-button>
        </div>
        <!-- 点击新建角色打开 -->
        <el-dialog v-model="visible" :show-close="false" width="550">
      <template #header="{ close }">
        <div class="my-header">
          <div>新建/修改通信塔</div>
          <el-button type="danger" @click="close">
            <el-icon class="el-icon"><CircleCloseFilled /></el-icon>
          </el-button>
        </div>
      </template>

      <!-- 输入框区域 -->
      <div style="display: flex;"></div>
      <div style="display: flex; flex-direction: column;">
  <div style="display: flex;">
    <div class="input-text"><span style="color: red;">*</span>所属机构:</div>
    <el-select v-model="value" placeholder="选择所属机构" style="width: 240px" @change="towerFormErrors.organization = false" filterable clearable>
        <el-option v-for="item in transformedSecondaryOrganizationList" :label="item.label" :value="item.value" />
      </el-select>
  </div>
  <p v-if="towerFormErrors.organization" class="error-text">所属机构不能为空</p>
</div>

    <div style="display: flex; flex-direction: column; margin-top: 1rem;">
  <div style="display: flex;">
    <div class="input-text"><span style="color: red;">*</span>地市:</div>
    <el-select v-model="city" placeholder="选择地市" style="width: 240px" @change="towerFormErrors.city = false">
        <el-option v-for="item in Prefectures" :label="item.label" :value="item.value" />
      </el-select>
  </div>
  <p v-if="towerFormErrors.city" class="error-text">请选择地市</p>
</div>


    <div style="display: flex; flex-direction: column; margin-top: 1rem;">
  <div style="display: flex;">
    <div class="input-text"><span style="color: red;">*</span>区县:</div>
    <el-select v-model="county" placeholder="选择区县" style="width: 240px" @change="towerFormErrors.county = false; onCountyChange(county) "  filterable
  clearable  
  >
        <el-option v-for="item in citys" :label="item.label" :value="item.value" />
      </el-select>
  </div>
  <p v-if="towerFormErrors.county" class="error-text">请选择区县</p>
</div>


    <div style="display: flex; flex-direction: column; margin-top: 1rem;">
  <div style="display: flex;">
    <div class="input-text"><span style="color: red;">*</span>站点名称:</div>
    <el-input v-model="towerName" style="width: 240px" @input="towerFormErrors.towerName = false" />
  </div>
  <p v-if="towerFormErrors.towerName" class="error-text">请输入站点名称</p>
</div>


<div style="display: flex; flex-direction: column; margin-top: 1rem;">
  <div style="display: flex;">
    <div class="input-text"><span style="color: red;">*</span>站点编码:</div>
    <el-input v-model="newTowerCode" style="width: 240px" />
  </div>
</div>

<div style="display: flex; flex-direction: column; margin-top: 1rem;">
  <div style="display: flex;">
    <div class="input-text"><span style="color: red;">*</span>通信塔类型：</div>
    <el-select 
      v-model="selectedTowerTypeId" 
      placeholder="请选择通信塔类型" 
      style="width: 240px"
      @change="handleTowerTypeChange"
      filterable
      clearable
    >
      <el-option 
        v-for="item in towerTypeOptions" 
        :key="item.value"
        :label="item.label" 
        :value="item.value" 
      />
    </el-select>
  </div>
  <p v-if="formErrors.towerType" class="error-text">请选择通信塔类型</p>
</div>

<!-- 平台层数选择（仅当选择的塔型有平台部位时显示） -->
<div 
  v-if="showPlatformCountSelect" 
  style="display: flex; flex-direction: column; margin-top: 1rem;"
>
  <div style="display: flex;">
    <div class="input-text"><span style="color: red;">*</span>平台层数：</div>
    <el-select 
      v-model="selectedPlatformCount" 
      placeholder="请选择平台层数" 
      style="width: 240px"
      @change="formErrors.platformCount = false"
    >
      <el-option 
        v-for="item in platformCountOptions" 
        :key="item.value"
        :label="item.label" 
        :value="item.value" 
      />
    </el-select>
  </div>
  <p v-if="formErrors.platformCount" class="error-text">请选择平台层数</p>
</div>


      <div 
        v-if="showBodyCountSelect"
       style="display: flex; flex-direction: column; margin-top: 1rem;">
  <div style="display: flex;">
    <div class="input-text"><span style="color: red;">*</span>塔身面数:</div>
    <el-select v-model="valueTowerCount" placeholder="请选择塔身面数" style="width: 240px" >
        <el-option v-for="item in towerCount" :label="item.label" :value="item.value" />
      </el-select>
  </div>
</div>


    <div style="display: flex;margin-top: 1rem">
        <div class="input-text">
         经度:
        </div>
        <el-input style="width: 240px" v-model=" longitude" ></el-input>
    </div>

    <div style="display: flex;margin-top: 1rem">
        <div class="input-text">
          纬度:
        </div>
        <el-input style="width: 240px" v-model=" latitude" ></el-input>
    </div>

    <div style="display: flex;margin-top: 1rem">
        <div class="input-text">
         海拔高度:
        </div>
        <el-input style="width: 240px" v-model="height" ></el-input>
    </div>


    <div style="display: flex; flex-direction: column; margin-top: 1rem;">
  <div style="display: flex;">
    <div class="input-text"><span style="color: red;">*</span>安装位置:</div>
    <el-select v-model="valuePosition" placeholder="请选择安装位置" style="width: 240px" @change="towerFormErrors.position = false">
        <el-option v-for="item in towerPosition" :label="item.label" :value="item.value" />
      </el-select>
  </div>
  <p v-if="towerFormErrors.position" class="error-text">请选择安装位置</p>
</div>


      <!-- 保存和取消按钮 -->
      <div style="margin-top: 2rem;position: relative;height: 3rem;">
        <div style="position: absolute;right: 0;">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="validateTowerForm() && sumbitMessage()">保存</el-button>
        </div>
      </div>
    </el-dialog>


    <el-table :data="displayedData" style="width: 95%; margin-top: 3rem;" class="auto-width-table">
  <el-table-column label="序号" >
    <template #default="{ row, $index }">
      <span v-if="row.tower">{{ (currentPage - 1) * pageSize + $index + 1 }}</span>
    </template>
  </el-table-column>

  <el-table-column prop="role.roleName" label="站点名称">
    <template #default="{ row }">
      <span  style="color: black;">{{ row.tower?.towerName }}</span>
    </template>
  </el-table-column>
  
  <el-table-column prop="role.roleName" label="通信塔类型" >
    <template #default="{ row }">
      <span  style="color: black;">{{ row.towerType?.typeName }}</span>
    </template>
  </el-table-column>

  <el-table-column prop="role.roleName" label="地市">
    <template #default="{ row }">
      <span  style="color: black;">{{ row.tower?.city }}</span>
    </template>
  </el-table-column>

  <el-table-column prop="role.roleName" label="区县" >
    <template #default="{ row }">
      <span  style="color: black;">{{ row.tower?.county }}</span>
    </template>
  </el-table-column>
  <el-table-column prop="role.createTime" label="创建时间" >
    <template #default="{ row }">
      <span  style="color: black;">{{ row.tower?.createTime }}</span>
    </template>
  </el-table-column>
  
  <el-table-column fixed="right" label="操作" >
    <template #default="{ row }">
      <div v-if="row.tower">
        <el-button link type="primary" size="small" @click="changeRole(row)"  v-if="hasPermission(authStore.permissions,19)" style="color: rgb(110, 78, 208);">编辑</el-button>
        <el-button link type="primary" size="small" @click="deleteTower(row)"   v-if="hasPermission(authStore.permissions,20)" style="color:#f56c6c;">删除</el-button>
      </div>
      <div v-else>
        <el-button link type="primary" size="small"  color="rgba(0,0,0,0)" >空</el-button>
      </div>
    </template>
  </el-table-column>
</el-table>
<!-- 这里写分页页面 -->

<el-pagination
  style="margin-top:2rem;"
  v-model:current-page="currentPage"
  v-model:page-size="pageSize"
  :total="total"
  layout="prev, pager, next, jumper"
  :background="true"
  @current-change="handleCurrentChange"
/>

    </div>


    <el-dialog v-model="deleteVisible" title="提示" width="500" center>
            <span>
              是否需要删除通信塔 "{{deleteItem.tower.towerName}}"
            </span>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="deleteVisible = false">取消</el-button>
              <el-button type="primary" @click="handleClick()">
               确认删除
            </el-button>
          </div>
        </template>
      </el-dialog>
</template>

<script lang="ts" setup>
    import { hasPermission } from '@/utils/permissionUtils';
    import { CircleCloseFilled , Plus} from '@element-plus/icons-vue';
    import { ref ,onMounted ,computed ,onUnmounted } from 'vue'
    import request from '@/utils/request';
    import { ElMessage } from 'element-plus';
    import {type UploadFile} from 'element-plus';
    import { useAuthStore } from '@/stores/user';
import showMessage from '@/utils/showMessage';
    const authStore = useAuthStore();//使用store仓库进行数据管理
    const selectedID= ref<any>()
    const fileList = ref<UploadFile[]>([]);

    const value = ref('')
    const options = <any>ref([])   //全部组织    
    const options1 = ref<any>([]);  //全部角色 
    
    const Name = ref();//姓名
    const Number = ref<any>();//手机号
    const tableData = ref([]); // 原始数据
    const displayedData = ref<any>([]); // 当前页显示的数据
    const currentPage = ref(1); // 当前页码
    const pageSize = ref(10); // 每页条数
    const total = ref(0); // 总条数
    const input = ref('')
    const userName = ref('')
    const userMessage = ref('')
    const visible = ref(false)
    const currentTab = ref(1)
    const flag = ref()//flag为1代表是新建，为2表示是修改

    const selectedTowerTypeId = ref<number | null>(null)
    const showPlatformCountSelect = ref(false) // 控制是否显示平台层数选择
    const showBodyCountSelect = ref(false) // 控制是否显示平台层数选择
    const selectedPlatformCount = ref<number | null>(null) // 选择的平台层数

    const formErrors = ref({
      towerType: false,
      platformCount: false
    })
    //塔身层数
    const platformCountOptions  = [
  {
    value: 1,
    label: '1',
  },
  {
    value: 2,
    label: '2',
  },
  {
    value: 3,
    label: '3',
  },
  {
    value: 4,
    label: '4',
  },
  {
    value: 5,
    label: '5',
  },
]
    //塔面数
    const towerCount = [

  {
    value: 3,
    label: '3',
  },
  {
    value: 4,
    label: '4',
  },
]
//位置
    const towerPosition = [

  {
    value: '地面',
    label: '地面',
  },
  {
    value: '楼面/屋面',
    label: '楼面/屋面',
  },
]

    const Prefectures = [
        {
            value: '阜阳市',
            label: '阜阳市',
        },
    ]
   
    const citys = [
        {
            value: '颍州区',
            label: '颍州区',
        },
        {
            value: '颍东区',
            label: '颍东区',
        },
        {
            value: '颍泉区',
            label: '颍泉区',
        },
        {
            value: '临泉县',
            label: '临泉县',
        },
        {
            value: '太和县',
            label: '太和县',
        },
        {
            value: '阜南县',
            label: '阜南县',
        },
        {
            value: '颍上县',
            label: '颍上县',
        },
        {
            value: '界首市',
            label: '界首市',
        },
    ]



const towerFormErrors = ref({
  organization: false,
  city: false,
  county: false,
  towerName: false,
  towerType: false,
  position: false
});


//这里是新建感铁塔需要的一些数据
const towerName = ref()//塔名
const towerCode = ref()//塔编号
const city = ref()//地市
const county = ref()//区县
const longitude = ref()
const latitude = ref()
const height = ref<number | null>()
const value1 = ref()//组织
const valueTowerCount = ref()//面数
const valuePosition = ref()//位置

// 这里是输入然后筛选
const inputCity = ref()
const inputCounty = ref()
const inputTowerTypeId =ref<number>()
const inputTowerName = ref()

const validateTowerForm = () => {
  towerFormErrors.value.organization = !value.value;
  towerFormErrors.value.city = !city.value;
  towerFormErrors.value.county = !county.value;
  towerFormErrors.value.towerName = !towerName.value?.trim();
  towerFormErrors.value.position = !valuePosition.value;

  return !Object.values(towerFormErrors.value).some(Boolean); // 所有字段非空才返回 true
};

// 处理通信塔类型变化
const handleTowerTypeChange = (towerTypeId: number) => {
  
  // 查找选中的塔型
  const selectedTower = towerTypeOptions.value?.find((item:any) => item.value === towerTypeId)
  
  // 更新是否显示平台层数选择
  
  showPlatformCountSelect.value = selectedTower?.hasPlatform || false

  showBodyCountSelect.value = selectedTower?.hasMultiFace || false
  
  // 如果切换的塔型没有平台部位，则清空已选的平台层数
  if (!showPlatformCountSelect.value) {
    selectedPlatformCount.value = null
  }
  
  // 重置错误状态
  formErrors.value.towerType = false
}



const countyCodeMap: Record<string, string> = {
  '颍州区': '341202',
  '颍东区': '341203',
  '颍泉区': '341204',
  '临泉县': '341221',
  '太和县': '341222',
  '阜南县': '341225',
  '颍上县': '341226',
  '界首市': '341282'
}
const newTowerCode  = ref()
const onCountyChange = (value: string) => {
  // 使用对象查找替代多个if-else
  towerCode.value = countyCodeMap[value] || ''
  
  // 调试输出
  console.log(`区县: ${value}, 编码: ${towerCode.value}`)
  
  // 如果需要可以在获取编码后执行其他操作
  if (towerCode.value) {
    const formData = new FormData()
  formData.append("administrativeCode" , towerCode.value)

  try {
    request.post("/resource/getRecentTowerCode", formData).then((res:any)=> {
      console.log(res.data);
      newTowerCode.value = res.data
    });
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败');
  }
  }
}

    // 新建
    const addTower = () => {
    towerFormErrors.value = {
  organization: false,
  city: false,
  county: false,
  towerName: false,
  towerType: false,
  position: false
};
      changeTowerId.value = ''
        towerName.value = ''
        newTowerCode.value = ''
        city.value = ''
        county.value = ''
        longitude.value = ''     
        latitude.value = ''
        height.value = null
        selectedPlatformCount.value = null
        valueTowerCount.value = ''
        valuePosition.value = ''
        value1.value = ''
        value.value = ''
      visible.value = true
      flag.value = 1
    }

    const filterUser = () => {      
  request.post("/resource/getTowerByCondition", {
    city: inputCity.value || '',
    county: inputCounty.value || '',
    towerTypeID: inputTowerTypeId.value || 0,
    towerName: inputTowerName.value || ''
  }).then((res) => {
    if (res.status == 200) {
      // 保存原始数据
      tableData.value = res.data;
      // 保存过滤后的数据
      filteredData.value = res.data;
      total.value = res.data.length;
      currentPage.value = 1;
      updateDisplayedData();
    }
  })
}
    // 删除逻辑
    const deleteVisible = ref(false)
    const deleteItem = ref()
    const deleteTower = (row:any) => {
      deleteVisible.value = true
      deleteItem.value = row
    }
// 修改 handleClick 删除函数
const handleClick = () => {
  request.post("/resource/deleteTower", {
    id: deleteItem.value.tower.id
  }).then((res) => {
    showMessage(res)
    if (res.status == 200) {
      // 从 filteredData 或 tableData 中删除
      if (filteredData.value.length > 0) {
        const index = filteredData.value.findIndex(item => item.tower?.id === deleteItem.value.tower.id);
        if (index !== -1) {
          filteredData.value.splice(index, 1);
        }
      } else {
        const index = tableData.value.findIndex((item:any) => item.tower?.id === deleteItem.value.tower.id);
        if (index !== -1) {
          tableData.value.splice(index, 1);
        }
      }
      
      // 更新总数和显示
      total.value -= 1;
      updateDisplayedData();
      
      // 日志记录
      request.post('/user/insertOperation', {
        username: authStore.user?.username,
        name: authStore.user?.name,
        organizationID: authStore.organizationID,
        ip: null,
        operationModel: "资源管理",
        operationResult: "删除通信塔成功",
        operationTime: null,
        operationType: "operation"
      })
      deleteVisible.value = false;
    }
  })
}

    // 修改逻辑
    const changeTowerId = ref()
    const changeTowerItem = ref()
    const changeRole = (row: any) => {
      console.log(row);
      

      handleTowerTypeChange(row.towerType.id)
      
    towerFormErrors.value = {
        organization: false,
        city: false,
        county: false,
        towerName: false,
        towerType: false,
        position: false
      };
        changeTowerItem.value = row
        changeTowerId.value = row.tower.id
        towerName.value = row.tower.towerName
        newTowerCode.value = row.tower.towerCode
        city.value = row.tower.city
        county.value = row.tower.county
        longitude.value = row.tower.longitude     
        latitude.value = row.tower.latitude
        height.value = row.tower.height
        selectedTowerTypeId.value = row.towerType.id
        selectedPlatformCount.value = row.tower.towerLayers
        valueTowerCount.value = row.tower.towerFaces
        valueTowerCount.value = row.tower.towerFaces
        valuePosition.value = row.tower.installationPosition
        value1.value = row.towerType.id
        value.value = row.organization.id
        // 提取权限数据
        visible.value = true;
        flag.value = 2;
};
// 引用树形组件

const sumbitMessage =() => {
  if(flag.value === 1) {    
    request.post('/resource/insertTower',{
        towerName:towerName.value,
        towerCode:newTowerCode.value,
        city:city.value,
        county:county.value,
        longitude:longitude.value,     
        latitude:latitude.value,
        height:height.value,
        towerLayers:selectedPlatformCount.value || null,
        towerFaces:valueTowerCount.value ,
        installationPosition:valuePosition.value,
        towerTypeID:selectedTowerTypeId.value,
        organizationID:value.value
    }).then((res)=>{
      showMessage(res)
      if(res.status == 200) {
        towerName.value = '',
        newTowerCode.value = '',
        city.value = '',
        county.value = '',
        longitude.value = '',     
        latitude.value = '',
        height.value =  null,
        selectedPlatformCount.value = null,
        valueTowerCount.value = '',
        valuePosition.value = '',
        selectedTowerTypeId.value = null,
        value.value = ''

         // 新建用户
         request.post('/user/insertOperation',{
                username : authStore.user?.username,
                name : authStore.user?.name,
                organizationID:authStore.organizationID,
                ip:null,
                operationModel:"资源管理",
                operationResult:"铁塔新建成功",
                operationTime:null,
                operationType:"operation"
              }).then(res => {
               
              })
        visible.value = false
        getAlltower()
      }
    })
  } else if (flag.value === 2 ) {
    request.post('/resource/updateTower',{
        id:changeTowerId.value,
        towerName:towerName.value,
        primaryTowerName:changeTowerItem.value.tower.towerName,
        towerCode:newTowerCode.value,
        city:city.value,
        county:county.value,
        longitude:longitude.value,     
        latitude:latitude.value,
        height:height.value,
        towerLayers:selectedPlatformCount.value,
        towerFaces:valueTowerCount.value,
        installationPosition:valuePosition.value,
        towerTypeID:selectedTowerTypeId.value,
        organizationID:value.value
    }).then((res)=>{
      showMessage(res)
      if(res.status == 200) {

        towerName.value = '',
        newTowerCode.value = '',
        city.value = '',
        county.value = '',
        longitude.value = '',     
        latitude.value = '',
        height.value =  null,
        selectedPlatformCount.value = null,
        valueTowerCount.value = '',
        valuePosition.value = '',
        value1.value = '',
        value.value = ''

         // 新建用户
         request.post('/user/insertOperation',{
                username : authStore.user?.username,
                name : authStore.user?.name,
                organizationID:authStore.organizationID,
                ip:null,
                operationModel:"资源管理",
                operationResult:"铁塔修改成功",
                operationTime:null,
                operationType:"operation"
              }).then(res => {
               
              })
        visible.value = false
        getAlltower()
      }
    })
  }
}

// 下载导入模板
const installTower = () => {
  request.get('/resource/downloadTemplate', { responseType: 'arraybuffer' }).then(res => {
    // 创建一个 Blob 对象，指定文件类型为 Excel
    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

    // 创建一个临时的下载链接
    const url = window.URL.createObjectURL(blob);

    // 创建一个下载链接元素
    const a = document.createElement('a');
    a.href = url;
    a.download = '导入模板.xlsx'; // 设置下载的文件名

    // 触发点击事件开始下载
    document.body.appendChild(a);
    a.click();

    // 下载完成后清除 URL 对象
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
  }).catch(error => {
    console.error('下载模板失败:', error);
  });
}


//导入
const inputValue = ref(false)
const inputTower = () => {
  fileList.value = []
  inputValue.value = true

}

// 处理文件变化
const handleFileChange = (file: UploadFile, files: UploadFile[]) => {
  fileList.value = files;
};



const upLoadMessage2 = async () => {
  if (fileList.value.length === 0) {
    ElMessage.error('请先选择文件');
    return;
  }

  const formData = new FormData();
  // 获取第一个文件的原始文件对象
  const file = fileList.value[0].raw;
  if (file && file instanceof File) {
    formData.append('file', file); // 确保 raw 是 File 类型
  } else {
    ElMessage.error('无效的文件类型');
    return;
  }

  try {
    const response = await request.post('/resource/uploadTemplate', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
    if (response.data.status === "fail") {
      ElMessage.error("导入失败，请重新配置");
    } else {
      ElMessage({
        message: '上传成功',
        type: 'success',
      });
      getAlltower()
    }
    inputValue.value = false; // 关闭弹窗
  } catch (error) {
    console.error('Upload failed:', error);
    ElMessage.error('上传失败，请重试');
  }
};




//导出
const outputTower = () => {
  request.get('/resource/exportTemplate', { responseType: 'arraybuffer' }).then(res => {
    // 创建一个 Blob 对象，指定文件类型为 Excel
    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

    // 创建一个临时的下载链接
    const url = window.URL.createObjectURL(blob);

    // 创建一个下载链接元素
    const a = document.createElement('a');
    a.href = url;
    a.download = '通信塔数据.xlsx'; // 设置下载的文件名

    // 触发点击事件开始下载
    document.body.appendChild(a);
    a.click();

    // 下载完成后清除 URL 对象
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
  }).catch(error => {
    console.error('下载模板失败:', error);
  });
}

// 获取全部角色信息
const getAllRole = () => {
  request.get('/user/getAllRole').then(
    (res)=>{
      if(res.data){
       if(res.data){
        options1.value = res.data.map((item:any) =>({
            value1:item.role.id,
            label:item.role.roleName
        }))
       }
      }
    }
  )
}

    // 获取所有二级组织相关
  // const OrganizationName = ref()
  const  SecondaryOrganizationList = ref([])
   const  getAllSecondaryOrganization = () => {
    request.get('/user/getAllSecondaryOrganization').then((res:any) => {
        SecondaryOrganizationList.value = res.data
    })
   }

   const transformedSecondaryOrganizationList = computed(() => {
    return SecondaryOrganizationList.value.map((item: any) => ({
        value: item.id,
        label: item.organizationName
    }));
});


// 获取全杆塔户信息
const getAlltower = () => {
  request.get('/resource/getAllTower').then(
    (res)=>{
   
      if(res.data){
        tableData.value = res.data
        total.value = res.data.length;
        updateDisplayedData();
      }
    }
  )
}
//获取全部塔类型数据
const AllTowerType = ref()//定义数据保存杆塔的所有的类别
const getAllTowerType = () => {
  request.get('/resource/getAllTowerType').then((res)=> {
  
  
    AllTowerType.value = res.data

  })
}

const towerType = ref() 

// key1:是否存在多面塔身部位，key2是否存在平台部位
const towerTypeOptions = computed(() => {
  return AllTowerType.value?.map((towerType:any) => {
    // 检查是否有"平台部位"
    const hasPlatform = towerType.towerPositions.some(
      (pos:any) => pos.positionType === '平台部位'
    )
    
    // 检查是否有"多面塔身部位"（如果需要）
    const hasMultiFace = towerType.towerPositions.some(
      (pos:any) => pos.positionType === '多面塔身部位'
    )

    return {
      value: towerType.towerType.id,
      label: towerType.towerType.typeName,
      hasPlatform,  // 是否有平台部位
      hasMultiFace  // 是否有多面塔身部位
    }
  })
})



// 添加一个 filteredData 的 ref
const filteredData = ref<any[]>([]);

// 修改 updateDisplayedData 函数
const updateDisplayedData = () => {
  // 使用 filteredData 或 tableData 作为数据源
  const dataSource = filteredData.value.length > 0 ? filteredData.value : tableData.value;
  
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  const currentData = dataSource.slice(start, end);

  // 填充空行以确保表格显示10行
  displayedData.value = Array.from({ length: pageSize.value }, (_, index) => currentData[index] || {});  
};

// 处理分页切换
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  updateDisplayedData();
};

  const detectPageSize = () => {
  const width = window.innerWidth;
  pageSize.value = width <= 1800 ? 10 : 20; // ≤1200px 时显示10条，>1200px 时显示20条
  updateDisplayedData();
};

  onMounted(()=>{
    detectPageSize(); // 初始调用
    window.addEventListener('resize', detectPageSize); // 直接监听resize事件，不使用防抖
    getAllRole()
    getAllSecondaryOrganization()
    getAlltower()
    getAllTowerType()
  })
  onUnmounted(() => {
  window.removeEventListener('resize', detectPageSize); // 移除事件监听
});

</script>

<style scoped>
.container {
    width: 100%;
    height: calc(100vh - 100px);
    display: block;
    padding: 20px;
    box-sizing: border-box;
}
.container-head {
    display: flex
} 
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}
.input-text {
    width: 20%;
    height: 2rem;
    line-height: 2rem;
    margin-left: 1rem;
}
.input-text1 {
    width: 10%;
    height: 2rem;
    line-height: 2rem;
    margin-left: 1rem;
}
.selected-tab {
  background-color: #409eff;
  color: white;
}
.empty-row {
  background-color: #f5f7fa;
  color: gray;
  text-align: center;
}
/* 表格自动宽度样式 */
.auto-width-table {
  table-layout: fixed; /* 关键属性 */
}

/* 定义各列宽度比例 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(1)) { width: 6%; }  /* 序号 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(2)) { width: 12%; } /* 任务名称 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(3)) { width: 12%; } /* 任务类型 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(4)) { width: 12%; } /* 通信塔类型 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(5)) { width: 12%; }  /* 地市 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(6)) { width: 24%; }  /* 区县 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(7)) { width: 24%; }  /* 巡视人员 */

/* 确保内容不溢出 */
.auto-width-table :deep(.cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .auto-width-table {
    min-width: 1000px; /* 在小屏幕上保持水平滚动 */
  }
}

.error-text {
  color: red;
  font-size: 12px;
  margin-left: 7.5rem;
  margin-top: 4px;
}

</style>